#include "chatserver.hpp"
#include "json.hpp"
#include "chatservice.hpp"

#include <functional>
#include <string>
using namespace std;
using namespace placeholders;
using json = nlohmann::json;

ChatServer:: ChatServer(EventLoop* loop,
              const InetAddress& listenAddr,
              const string& nameArg)
    : chat_server(loop,listenAddr,nameArg),chat_loop(loop)
{
    //注册连接回调
    chat_server.setConnectionCallback(std::bind(&ChatServer::onConnection,this,_1));

    //注册信息回调
    chat_server.setMessageCallback(std::bind(&ChatServer::onMessage,this,_1,_2,_3));

    //设置线程数量
    chat_server.setThreadNum(4);
    
}
//启动服务
void ChatServer::start()
{
    chat_server.start();
}

void ChatServer::onConnection(const TcpConnectionPtr &conn)
{
    if(!conn->connected())
    {
        ChatService::instance()->clientCloseException(conn);
        conn->shutdown();
    }
}

void ChatServer::onMessage(const TcpConnectionPtr &conn,
                Buffer *buffer,
                Timestamp time)
{
    string buf=buffer->retrieveAllAsString();
    //数据的反序列化
    json js=json::parse(buf);
    //希望完全解耦网络模块和业务模块的代码
    //通过js【“msgid”】获取一个业务处理器handler->conn js time
    auto msgHandle =ChatService::instance()->getHandle(js["msgid"].get<int>());
    //回调消息绑定好的事件处理器，来执行相应的业务处理
    msgHandle(conn,js,time);

}